package com.example.blockchain.service.impl;


import com.example.blockchain.entity.TradeObject;
import com.example.blockchain.entity.block.*;
import com.example.blockchain.timer.UpdateTimer;
import com.example.blockchain.utils.BlockBaseUtils;
import com.example.blockchain.utils.http.HttpHelper;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DataDealServiceImpl{



    public void updateBlock(String blockIndex, Mining mining, MapFriends map) throws Exception {
        BlockDownLoad bdl = null;
        for(String port:map.getFs().keySet()){
            Friends f= map.getFs().get(port);
            String ip=f.getIp();
            if (f.getFriendliness() == 0){
                continue;
            }
            NoticeParams np = new NoticeParams(blockIndex.toString(), ip,"");
            bdl = HttpHelper.downLoadBlock(ip, 8001, np);//获取区块和区块内容
            if(bdl == null) {
                continue;
            }

            //检测当前区块是否已经存在
            TradeBodyPool tbp = BlockBaseUtils.genTbp(bdl);
            List<Block> bs=BlockServiceImpl.queryBlockByBlockIndex(bdl.getBlock().getBlockIndex());
            if(bs.size() > 0 ){
                deletePending(tbp);//删除pending
                return;
            }
            BlockServiceImpl.checkBlockTable(bdl.getBlock().getBlockIndex());//检查表是否存在

            BlockServiceImpl.save(bdl.getBlock());//保存区块DB
            BlockServiceImpl.saveBlockFile(bdl);//保存区块文件
            DicServiceImpl.updateDicBlockIndex(blockIndex);//更新当前更新到的块号
            DicServiceImpl.updateDicMainBockIndex(bdl.getMaxBlockIndex());//更新当前更新到的块号
            UpdateTimer.currentBlockIndex= new BigInteger(blockIndex) ;
            UpdateTimer.currentMaxBlockIndex= new BigInteger(bdl.getMaxBlockIndex()) ;
            deletePending(tbp);//删除pending

            break;
        }
        if(bdl==null){
            mining.updateComplete=true;
            mining.isWork=true;
            //已经更新到最高区块
            throw new Exception();
        }
    }
    public void deletePending(TradeBodyPool tbp) {
        List<String> tradeNos = new ArrayList<String>();
        Map<String, TradeObject> tbMap = tbp.getTbMap();
        for(Map.Entry<String, TradeObject> entry : tbMap.entrySet()) {
            tradeNos.add(entry.getValue().getHashNo());
        }
        PendingServiceImpl.deletePendings(tradeNos);//删除已经入块验证过的信息

    }

}
